from django.views import View

from Venue.models import Venue, Vip, VenueSportYard, Coupon
from sportsground.utils import Req
from sportsground.utils.Res import Res
from sportsground.utils.views import LoginRequired


class CouponView(View):
    """ 优惠券 """

    def get(self, request):
        """ 查询 """
        venue = Venue.objects.get(id=1)
        coupons = Coupon.objects.filter(venue=venue)
        lists = []
        for coupon in coupons:
            lists.append(coupon.Info())
        return Res.Json(Res.OK, result=lists)

    @LoginRequired.Venue
    @Req.getJson
    def post(self, request):
        """ 添加 """
        name = request.json_dict.get("name")
        desc = request.json_dict.get("desc")
        reach = request.json_dict.get("reach")
        derate = request.json_dict.get("derate")
        startTime = request.json_dict.get("startTime")
        endTime = request.json_dict.get("endTime")

        venue = request.user.venue

        coupon = Coupon.create(venue,name,desc,reach,derate,startTime,endTime)
        return Res.Json(Res.OK, result=coupon.Info())

    @LoginRequired.Venue
    @Req.getJson
    def put(self, request):
        """ 修改 """
        id = request.json_dict.get("id")
        name = request.json_dict.get("name")
        desc = request.json_dict.get("desc")
        reach = request.json_dict.get("reach")
        derate = request.json_dict.get("derate")
        startTime = request.json_dict.get("startTime")
        endTime = request.json_dict.get("endTime")

        venue = request.user.venue
        coupon = Coupon.objects.filter(venue=venue, id=id).first()
        if not coupon:
            return Res.Json(Res.ParamErr)

        if name:
            coupon.name = name
        if desc:
            coupon.desc = desc
        if reach:
            coupon.reach = reach
        if derate:
            coupon.derate = derate
        if startTime:
            coupon.startTime = startTime
        if endTime:
            coupon.endTime = endTime

        coupon.save()
        return Res.Json(Res.OK, result=coupon.Info())

    @LoginRequired.Venue
    @Req.getJson
    def delete(self, request):
        """ 删除 """
        id = request.json_dict.get("id")

        venue = request.user.venue

        coupon = Coupon.objects.filter(venue=venue, id=id).first()
        if not coupon:
            return Res.Json(Res.ParamErr)

        coupon.delete()
        return Res.Json(Res.OK)
